<template>
  <AForm>
    <a-form-item label="事件位置">
      <a-row :gutter="10">
        <a-col :span="20">
          <div v-if="formState.areaType == 1">
            <a-input v-model:value="searchText" @change="handleSearch" />
            <div v-if="searchResult.length > 0">
              <a-list>
                <a-list-item
                  v-for="(item, index) in searchResult"
                  @click="handleSelectResult(item)"
                >
                  <a-list-item-meta
                    :title="item.name"
                    :description="item.address"
                  />
                </a-list-item>
              </a-list>
            </div>
          </div>

          <a-row v-if="formState.areaType == 2" :gutter="[12]">
            <a-col :span="12"
              ><a-input v-model:value="formState.longitude"
            /></a-col>
            <a-col :span="12"
              ><a-input v-model:value="formState.latitude"
            /></a-col>
          </a-row>
          <div v-if="formState.areaType == 3">
            <a-input v-model:value="searchText" @change="handleSearch" />
          </div>
        </a-col>
        <a-col :span="4">
          <a-select v-model:value="formState.areaType">
            <a-select-option v-for="item in areaTypeList" :value="item.value">{{
              item.label
            }}</a-select-option>
          </a-select>
        </a-col>
        <a-col
          :span="24"
          v-if="formState.areaType == 1 || formState.areaType == 3"
        >
          <div ref="mapContainer" class="map-container"></div>
        </a-col>
      </a-row>
    </a-form-item>
  </AForm>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";

// 声明天地图类型
declare global {
  interface Window {
    T: any;
    TMAP_HYBRID_MAP: any;
  }
}
let areaTypeList = ref([
  { label: "按地点名称", value: 1 },
  { label: "地图选点", value: 3 },
  { label: "按经纬度", value: 2 },
]);
let formState = ref({
  eventCode: "",
  name: "",
  eventTime: "",
  eventTime1: "",
  eventPlace: "",
  longitude: "",
  latitude: "",
  eventDetails: "",
  districtId: "",
  sceneCode: "WXHXP",
  areaType: 1,
});
const mapContainer = ref<HTMLElement>();
const currentLngLat = ref<any>();
const zoom = ref(12);
let marker: any = null;
let map: any = null;
const scale = ref(1);
let localSearch: any = null;
const searchResult = ref([]);
const searchText = ref("");
const getScale = () => {
  scale.value = 3840 / window.innerWidth;
  if (scale.value < 1) {
    scale.value = 1;
  }
};
const initMap = () => {
  let T = window.T;
  if (map) {
    document.getElementById("map")?.replaceChild();
    map = null;
  }
  if (T) {
    try {
      map = new T.Map(mapContainer.value, {
        projection: "EPSG:4326",
      });
      map.setMapType(window.TMAP_HYBRID_MAP);
      map.centerAndZoom(new T.LngLat(121.612411, 29.853798), zoom.value);
      getScale();
      const config = {
        pageCapacity: 10,
        onSearchComplete: handleSearchComplete, // 接收数据的回调函数
      };
      locaSearch = new T.localSearch(map, config);

      map.addEventListener("click", function (e) {
        const lngLat = e.lnglat;
        const rect = map.lngLatToContainerPoint(e.lnglat);

        const x = rect.x * scale.value;
        const y = rect.y * scale.value;

        const lnglatR = map.containerPointToLngLat(new T.Point(x, y));

        let geocoder = new T.Geocoder();
        geocoder.getLocation(lnglatR, searchResult);
        function seatchResult(results) {
          searchText.value = results.formatted_address;
        }

        updateMarker(lnglatR.lng, lnglatR.lat);
      });
    } catch (err) {}
  } else {
  }
};

const handleSearch = () => {
  if (!localSearch) {
    initMap();
  }
  if (!searchText.value.trim()) {
    searchResult.value = [];
    return;
  }
  localSearch.search(searchText.value);

  // 如果搜索结果只有一个，自动选中并更新经纬度
  localSearch.setSearchCompleteCallback((result) => {
    if (result && result.count === 1 && result.pois && result.pois.length > 0) {
      const item = result.pois[0];
      item.lonlatArr = item.lonlat.split(",");
      const searchItem = {
        name: item.name,
        address: item.address,
        lng: item.lonlatArr[0],
        lat: item.lonlatArr[1],
      };
      handleSelectResult(searchItem);
    }
  });
};
const handleSearchComplete = (result) => {
  if (result && result.count > 0 && result.pois) {
    searchResult.value = [];
    result.pois.forEach((item) => {
      item.lonlatArr = item.lonlat.split(",");
      searchResult.value.push({
        name: item.name,
        address: item.address,
        lng: item.lonlatArr[0],
        lat: item.lonlatArr[1],
      });
    });
  } else {
    searchResult.value = [];
  }
};

const updateMarker = (lng, lat) => {
  if (marker) {
    map.removeOverLay(marker);
  }
  currentLngLat.value = [lng.toFixed(5), lat.toFixed(5)];
  lonlatInput.value = [lng.toFixed(5), lat.toFixed(5)];
  marker = new T.Marker(new T.LngLat(currentLngLat[0], currentLngLat[1]));
  map.addOverLay(marker);
};

const handleSelectResult = (item) => {
  if (!localSearch) {
    initMap();
  }

  searchText.value = item.name;
  searchResult.value = [];

  // 更新地图标记
  updateMarker(item.lng, item.lat);

  // 更新表单中的经纬度值
  formState.value.longitude = item.lng;
  formState.value.latitude = item.lat;

  // 将地图中心移动到选中位置并放大
  map.centerAndZoom(new T.LngLat(item.lng, item.lat), 15);
};

watch(
  () => formState.value.areaType,
  (newValue, oldValue) => {
    if (newValue == 1 || newValue == 3) {
      initMap();
    } else {
      mapContainer.value.innerHTML = "";
      map = null;
      marker = null;
      localSearch = null;
      currentLngLat.value = null;
      zoom.value = 12;
    }
  }
);
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 200px;
  min-height: 200px;
  position: relative;
}
</style>
